#include "tcpclientmanager.h"
#include <QDebug>
#include "message.h"

TcpClientManager::TcpClientManager(QObject *parent) :
    QObject(parent)
{
    _hasStx = false;
    _hasEtx = false;
    _tcpClient = NULL;
    //_buffer = '';
}

void TcpClientManager::setTcpClient(QTcpSocket *tcpClient)
{
    qDebug()<<"TcpClientManager::setTcpClient(QTcpSocket *tcpClient)";
    _tcpClient = tcpClient;
    connect(_tcpClient, SIGNAL(readyRead()),
        this, SLOT(startRead())
    );
    connect(_tcpClient, SIGNAL(disconnected()),
        this, SLOT(clientDisconnect())
    );
    connect(_tcpClient, SIGNAL(destroyed()),
            this, SLOT(clientDestroyed())
    );

}
void TcpClientManager::processIncommingData(const QByteArray &buffer)
{
    qDebug()<<"TcpClientManager::processIncommingData(const QByteArray &buffer)";
    for(int index=0;index<buffer.size();index++)
    {
        if(!_hasStx && buffer[index]==Message::CTRL_STX)
        {
            _hasStx = true;
            _hasEtx = false;
            qDebug()<<"Starting new message";
            _buffer.append(buffer[index]);
        }
        else if(_hasStx && buffer[index]==Message::CTRL_ETX)
        {
            _hasStx = false;
            _hasEtx = true;
            _buffer.append(buffer[index]);
            qDebug()<<"End new message: ["<<_buffer<<"]";
            emit receivedMessage(_buffer);
            _buffer.clear();
        }
        else if(_hasStx&&!_hasEtx)
        {
            qDebug()<<"appending data ["<<buffer[index]<<"]";
            _buffer.append(buffer[index]);
        }
        else
        {
            qDebug()<<"unexpected incomming data ["<<buffer[index]<<"]";
            //qDebug()<<"unexpected incomming data as HEX["<<buffer[index].to <<"]";
        }
    }
}

void TcpClientManager::startRead()
{
    qDebug()<<"TcpClientManager::startRead()";
    QByteArray buffer;
    buffer = _tcpClient->read(_tcpClient->bytesAvailable());
    qDebug()<<"[" <<buffer <<"]"<<endl;
    processIncommingData(buffer);
}
void TcpClientManager::sendData(QByteArray data)
{
    qDebug()<<"TcpClientManager::sendData(QByteArray data)";
    if(valid())
    {
        qDebug()<<"Valid connection";
        _tcpClient->write(data);
    }else
    {
        qDebug()<<"Invalid connection";
    }

}
bool TcpClientManager::valid()
{
    qDebug()<<"TcpClientManager::valid()";
    return _tcpClient!=NULL&&_tcpClient->isOpen()&&_tcpClient->isValid()&&_tcpClient->isWritable();
}
void TcpClientManager::clientDisconnect()
{
    qDebug()<<"TcpClientManager::clientDisconnect()";
    QObject * sender = this->sender();
    sender->deleteLater();
}
void TcpClientManager::clientDestroyed()
{
    qDebug()<<"TcpClientManager::clientDestroyed()";
    _tcpClient = NULL;
}
QTcpSocket* TcpClientManager::getTcpClient()
{
    qDebug()<<"TcpClientManager::getTcpClient()";
    return _tcpClient;
}
